<template>
  <div class="integrity-building-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button 
        @click="goBack" 
        :icon="ArrowLeft" 
        circle 
        size="small"
        class="back-btn"
      />
      <h2 class="page-title">诚信五化建设详情</h2>
      <el-button 
        type="primary" 
        size="small" 
        @click="refreshData"
        :loading="loading"
        :icon="Refresh"
      >
        刷新
      </el-button>
    </div>

    <!-- 季度信息 -->
    <div class="quarter-info-card">
      <div class="quarter-header">
        <el-icon class="quarter-icon"><Calendar /></el-icon>
        <span class="quarter-title">{{ currentQuarter }}季度诚信五化建设</span>
      </div>
      <div class="quarter-details">
        <div class="detail-item">
          <span class="detail-label">服务周期：</span>
          <span class="detail-value">每季度完成一次</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">截止时间：</span>
          <span class="detail-value" :class="{ 'urgent': remainingDays <= 7 }">
            {{ quarterEndDate }}（剩余{{ remainingDays }}天）
          </span>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-tabs">
        <el-segmented 
          v-model="activeFilter" 
          :options="filterOptions"
          @change="onFilterChange"
        />
      </div>
      
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索客户代码或店名"
          @input="onSearch"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-summary">
      <div class="summary-item">
        <div class="summary-number">{{ filteredClients.length }}</div>
        <div class="summary-label">当前显示</div>
      </div>
      <div class="summary-item">
        <div class="summary-number">{{ stats.completedCount }}</div>
        <div class="summary-label">已完成</div>
      </div>
      <div class="summary-item">
        <div class="summary-number">{{ stats.uncompletedCount }}</div>
        <div class="summary-label">未完成</div>
      </div>
      <div class="summary-item">
        <div class="summary-number">{{ completionPercentage }}%</div>
        <div class="summary-label">完成率</div>
      </div>
    </div>

    <!-- 客户列表 -->
    <div class="clients-container">
      <div class="clients-list" v-if="filteredClients.length > 0">
        <div 
          v-for="client in filteredClients" 
          :key="client.id"
          class="client-card"
          :class="{ 'completed': client.isCompleted }"
        >
          <div class="client-header">
            <div class="client-info">
              <h4 class="client-name">{{ client.clientName }}</h4>
              <span class="client-code">{{ client.clientCode }}</span>
            </div>
            <div class="client-status">
              <el-tag 
                :type="client.isCompleted ? 'success' : 'danger'"
                size="small"
              >
                {{ client.isCompleted ? '已完成' : '未完成' }}
              </el-tag>
            </div>
          </div>

          <div class="client-details">
            <div class="detail-row">
              <el-tag size="small">{{ client.marketType }}</el-tag>
              <el-tag size="small" type="info">{{ client.terminalType }}</el-tag>
            </div>
            
            <div class="service-requirement">
              服务要求：每季度完成一次诚信体系建设指导
            </div>

            <!-- 已完成客户显示完成记录 -->
            <div class="completion-records" v-if="client.isCompleted && client.recentRecords">
              <div class="records-title">本季度完成记录：</div>
              <div class="records-list">
                <div 
                  v-for="record in client.recentRecords.slice(0, 1)" 
                  :key="record.id"
                  class="record-item"
                >
                  <span class="record-date">{{ formatDate(record.completionDate) }}</span>
                  <span class="record-notes" v-if="record.notes">{{ record.notes }}</span>
                </div>
              </div>
            </div>

            <!-- 未完成客户显示操作按钮 -->
            <div class="client-actions" v-if="!client.isCompleted">
              <el-button 
                size="small" 
                type="primary"
                @click="addCompletionRecord(client)"
              >
                添加完成记录
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="empty-state" v-else>
        <el-empty :description="getEmptyDescription()" :image-size="100">
          <el-button 
            type="primary" 
            @click="goToWorkLog"
            v-if="activeFilter === 'uncompleted'"
          >
            添加完成记录
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 添加完成记录对话框 -->
    <el-dialog
      v-model="showAddRecordDialog"
      title="添加诚信五化建设完成记录"
      width="90%"
    >
      <div class="selected-client-info" v-if="selectedClient">
        <h4>{{ selectedClient.clientName }}</h4>
        <p>客户代码：{{ selectedClient.clientCode }}</p>
        <p>终端类型：{{ selectedClient.terminalType }}</p>
      </div>

      <el-form :model="recordForm" label-position="top">
        <el-form-item label="完成日期">
          <el-date-picker
            v-model="recordForm.completionDate"
            type="date"
            placeholder="选择完成日期"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="工作内容">
          <el-input
            v-model="recordForm.notes"
            type="textarea"
            :rows="4"
            placeholder="请详细描述诚信五化建设的具体工作内容和成果"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddRecordDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitCompletionRecord"
          :loading="submitting"
          :disabled="!recordForm.completionDate"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Refresh,
  Search,
  Calendar
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const activeFilter = ref('all')
const searchKeyword = ref('')
const allClients = ref([])
const stats = ref({
  totalClients: 0,
  completedCount: 0,
  uncompletedCount: 0
})
const showAddRecordDialog = ref(false)
const selectedClient = ref(null)

// 表单数据
const recordForm = ref({
  completionDate: null,
  notes: ''
})

// 筛选选项
const filterOptions = [
  { label: '全部', value: 'all' },
  { label: '已完成', value: 'completed' },
  { label: '未完成', value: 'uncompleted' }
]

// 计算属性
const filteredClients = computed(() => {
  let clients = allClients.value

  // 按状态筛选
  if (activeFilter.value === 'completed') {
    clients = clients.filter(client => client.isCompleted)
  } else if (activeFilter.value === 'uncompleted') {
    clients = clients.filter(client => !client.isCompleted)
  }

  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    clients = clients.filter(client => 
      client.clientName.toLowerCase().includes(keyword) ||
      client.clientCode.toLowerCase().includes(keyword)
    )
  }

  return clients
})

const completionPercentage = computed(() => {
  const completed = stats.value.completedCount || 0
  const total = stats.value.totalClients || 0
  
  if (total === 0) {
    return completed > 0 ? 100 : 0 // 如果没有总数但有完成数，则为100%
  }
  
  const percentage = Math.round((completed / total) * 100)
  return isNaN(percentage) ? 0 : percentage
})

const currentQuarter = computed(() => {
  const month = new Date().getMonth() + 1
  return Math.ceil(month / 3)
})

const quarterEndDate = computed(() => {
  const year = new Date().getFullYear()
  const quarter = currentQuarter.value
  const endMonth = quarter * 3
  const endDate = new Date(year, endMonth, 0)
  return `${endMonth}月${endDate.getDate()}日`
})

const remainingDays = computed(() => {
  const year = new Date().getFullYear()
  const quarter = currentQuarter.value
  const endMonth = quarter * 3
  const endDate = new Date(year, endMonth, 0)
  const today = new Date()
  const diffTime = endDate.getTime() - today.getTime()
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

// 方法
const goBack = () => {
  router.back()
}

const loadData = async () => {
  try {
    loading.value = true
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取诚信五化建设服务的ID（从服务列表中查找"诚信五化建设"）
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const integrityService = services.find((s: any) => s.serviceName?.includes('诚信五化建设'))
    const integrityServiceId = integrityService?.id

    if (!integrityServiceId) {
      console.warn('未找到诚信五化建设服务')
      stats.value = {
        totalClients: 0,
        completedCount: 0,
        uncompletedCount: 0
      }
      allClients.value = []
      return
    }

    // 计算本季度时间范围
    const { startDate, endDate } = getCurrentQuarterRange()

    const result = await trpc.workLog.serviceStats.query({
      managerId,
      serviceId: integrityServiceId,
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString()
    })

    if (result.success) {
      stats.value = {
        totalClients: result.data.totalClients,
        completedCount: result.data.completedCount,
        uncompletedCount: result.data.uncompletedCount
      }

      // 合并已完成和未完成的客户，添加完成状态标记
      const completedClients = (result.data.completedClients || []).map(client => ({
        ...client,
        isCompleted: true,
        recentRecords: result.data.recentLogs?.filter(log => log.clientId === client.id) || []
      }))

      const uncompletedClients = (result.data.uncompletedClients || []).map(client => ({
        ...client,
        isCompleted: false,
        recentRecords: []
      }))

      allClients.value = [...completedClients, ...uncompletedClients]
    }
  } catch (error) {
    console.error('加载诚信五化建设详情失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const getCurrentQuarterRange = () => {
  const now = new Date()
  const quarter = Math.ceil((now.getMonth() + 1) / 3)
  const startMonth = (quarter - 1) * 3
  const startDate = new Date(now.getFullYear(), startMonth, 1)
  const endDate = new Date(now.getFullYear(), startMonth + 3, 0)
  return { startDate, endDate }
}

const onFilterChange = () => {
  // 筛选变化时的处理
}

const onSearch = () => {
  // 搜索时的处理（已通过计算属性实现）
}

const refreshData = () => {
  loadData()
}

const formatDate = (dateStr: string) => {
  // 解析日期字符串，避免时区问题
  if (dateStr.includes('T')) {
    // 如果是完整的ISO日期时间字符串，直接使用Date构造函数
    const date = new Date(dateStr)
    return `${date.getMonth() + 1}月${date.getDate()}日`
  } else {
    // 如果是纯日期字符串，手动解析避免时区问题
    const [year, month, day] = dateStr.split('-').map(Number)
    return `${month}月${day}日`
  }
}

const getEmptyDescription = () => {
  if (activeFilter.value === 'completed') {
    return '暂无已完成的诚信五化建设'
  } else if (activeFilter.value === 'uncompleted') {
    return '暂无未完成的诚信五化建设'
  }
  return '暂无客户数据'
}

const addCompletionRecord = (client: any) => {
  selectedClient.value = client
  recordForm.value = {
    completionDate: new Date(),
    notes: ''
  }
  showAddRecordDialog.value = true
}

const disabledDate = (time: Date) => {
  // 不能选择未来的日期
  return time.getTime() > Date.now()
}

const submitCompletionRecord = async () => {
  if (!recordForm.value.completionDate || !selectedClient.value) return

  submitting.value = true
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取诚信五化建设服务的ID（从服务列表中查找"诚信五化建设"）
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const integrityService = services.find((s: any) => s.serviceName?.includes('诚信五化建设'))
    const integrityServiceId = integrityService?.id

    if (!integrityServiceId) {
      ElMessage.error('未找到诚信五化建设服务')
      return
    }

    await trpc.workLog.create.mutate({
      managerId,
      clientId: selectedClient.value.id,
      serviceId: integrityServiceId,
      completionDate: recordForm.value.completionDate.toISOString(),
      notes: recordForm.value.notes || undefined
    })

    ElMessage.success('诚信五化建设完成记录添加成功')
    showAddRecordDialog.value = false
    await loadData()
  } catch (error) {
    console.error('添加完成记录失败:', error)
    ElMessage.error('添加完成记录失败')
  } finally {
    submitting.value = false
  }
}

const goToWorkLog = () => {
  router.push('/work-log')
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  return user?.id || null
}

// 监听路由查询参数变化
watch(() => route.query.filter, (newFilter) => {
  if (newFilter && newFilter !== activeFilter.value) {
    activeFilter.value = newFilter as string
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.integrity-building-detail-page {
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.back-btn {
  width: 32px;
  height: 32px;
}

.quarter-info-card {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  margin: 12px;
  border-radius: 8px;
  padding: 16px;
}

.quarter-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.quarter-icon {
  color: #1890ff;
  margin-right: 8px;
}

.quarter-title {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
}

.quarter-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  font-size: 14px;
  color: #0050b3;
  margin-right: 8px;
}

.detail-value {
  font-size: 14px;
  color: #0050b3;
  font-weight: 500;
}

.detail-value.urgent {
  color: #f5222d;
}

.filter-section {
  background: white;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.filter-tabs {
  margin-bottom: 16px;
}

.search-bar {
  width: 100%;
}

.stats-summary {
  display: flex;
  background: white;
  margin: 12px;
  border-radius: 8px;
  padding: 16px;
  gap: 16px;
}

.summary-item {
  flex: 1;
  text-align: center;
}

.summary-number {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.summary-label {
  font-size: 12px;
  color: #909399;
}

.clients-container {
  margin: 12px;
}

.clients-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.client-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  border-left: 4px solid #f56c6c;
}

.client-card.completed {
  border-left-color: #67c23a;
}

.client-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 12px;
}

.client-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
}

.client-code {
  font-size: 12px;
  color: #909399;
}

.client-details {
  space-y: 8px;
}

.detail-row {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.service-requirement {
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.completion-records {
  background: #f0f9ff;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.records-title {
  font-size: 12px;
  color: #0369a1;
  margin-bottom: 4px;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.record-item {
  display: flex;
  gap: 8px;
  font-size: 12px;
}

.record-date {
  color: #0369a1;
  font-weight: 500;
}

.record-notes {
  color: #075985;
  flex: 1;
}

.client-actions {
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  padding: 40px 20px;
  background: white;
  border-radius: 8px;
}

.selected-client-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.selected-client-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.selected-client-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}

:deep(.el-segmented) {
  width: 100%;
}

:deep(.el-segmented__item) {
  flex: 1;
}

:deep(.el-dialog) {
  margin-top: 5vh;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
